package me.zhengjie.config.word.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import me.zhengjie.config.FileProperties;
import me.zhengjie.config.enums.TemplateEnum;
import me.zhengjie.config.exception.WeChatException;
import me.zhengjie.modules.system.domain.ExamResult;
import me.zhengjie.modules.system.service.dto.ReportChartDto;
import me.zhengjie.service.LocalStorageService;
import me.zhengjie.service.dto.LocalStorageDto;
import me.zhengjie.utils.DateUtil;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.StringUtils;
import org.ddr.poi.html.HtmlRenderPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

@Component
public class WordCreateUtil {
    private static final Logger log = LoggerFactory.getLogger(WordCreateUtil.class);

    @Value("${domain.url}")
    private String domainUrl;

    @Autowired
    LocalStorageService localStorageService;

    @Autowired
    FileProperties properties;

    /**
     *
     * @param resultDto
     * @return
     * @throws Exception
     */
    public String createWord(ExamResult resultDto) throws Exception {
        ReportChartDto reportChartDto = JSONUtil.toBean(resultDto.getReportJson(), ReportChartDto.class);
        BeanUtil.copyProperties(resultDto,reportChartDto);
        Map<String,Object> report = ChangDto2ChartViewUtil.convert(reportChartDto);
        putHeightScore(reportChartDto,report);
        String templateName = TemplateEnum.getTemplate(resultDto.getAtmrType(),reportChartDto.getAgeType());
        if(StringUtils.isEmpty(templateName)){
            throw new WeChatException("该测评报告模版未配置");
        }
        LocalStorageDto localStorageDto = localStorageService.findByName(templateName);
        String filePath = properties.getPath().getPath().replaceFirst( properties.getPath().getNgx(),"");
        String url = domainUrl + filePath + localStorageDto.getType() + File.separator + localStorageDto.getRealName();
        //String url = "http://43.143.97.111/file/texts/" + localStorageDto.getRealName();
        return print(report,url,resultDto.getUuid()+".docx");
    }

    /**
     * 关键特质
     * @param reportChartDto
     * @param report
     */
    private void putHeightScore(ReportChartDto reportChartDto,Map<String,Object> report){
        if(CollectionUtils.isEmpty(reportChartDto.getHeightScore())){
            return;
        }
        List<Map<String,String>> keys = new ArrayList<>();
        for (String kv : reportChartDto.getHeightScore()) {
            if(StringUtils.isEmpty(kv)){
                continue;
            }

            String[] values = kv.split(";");
            if(values.length<2){
                continue;
            }
            Map<String,String> map = new HashMap<>();
            map.put("keyName",values[0]);
            map.put("keyValue",values[1]);
            keys.add(map);
        }
        if(CollectionUtils.isEmpty(keys)){
            return;
        }
        report.put("keys",keys);
    }

    /**
     * 输出DOCX文件
     *
     * @param report
     * @param outFile
     */
    public String print(Map<String, Object> report,String templateUrl, String outFile) throws Exception {

        String filePath = properties.getPath().getPath()
                + FileUtil.REPORT
                + File.separator
                + DateUtil.localDateTimeFormat(DateUtil.toLocalDateTime(new Date()), "yyyyMMdd")
                + File.separator;
        String tmpPath = filePath + outFile;
        URL httpUrl = new URL(templateUrl);
        //URL httpUrl = new URL("http://43.143.97.111/file/texts/chengren-zhuanye-20231120091605588.docx");
        URLConnection connection = httpUrl.openConnection();

        ConfigureBuilder builder = Configure.builder();
        //builder.bind("zuoYouLiLun",new HtmlRenderPolicy());
        builder.addPlugin('%', new HtmlRenderPolicy());
        XWPFTemplate template = XWPFTemplate.compile(connection.getInputStream(),builder.build());
        template.render(report);
        File file = FileUtil.getFile(tmpPath);
        //String path =  "/Users/zhaoxiancheng/Downloads/"+ outFile;
        template.writeAndClose(new FileOutputStream(file));
        String reportPath = tmpPath;
        return reportPath.replace(properties.getPath().getNgx(), "");
    }


}
